//
//  XSM3u8ListViewController.m
//  XSDownloadDemo
//
//  Created by 大帅 on 2023/12/29.
//

#import "XSM3u8ListViewController.h"

#import "XSM3u8TableViewCell.h"        // cell
#import "XSPlayViewController.h"       // 播放页面

// cell标识符
static NSString *m3u8TableViewCellId = @"XSM3u8TableViewCellId";

@interface XSM3u8ListViewController () <UITableViewDelegate, UITableViewDataSource>
/** 列表视图 */
@property (nonatomic, strong) UITableView *tableView;
/** 数据 */
@property (nonatomic, strong) NSMutableArray *dataArray;
/** 导航右侧按钮 */
@property (nonatomic, strong) UIButton *allBtn;

@end

@implementation XSM3u8ListViewController

-(NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
        
        NSArray *urlList = @[
            @"https://bp-resource-cc.bestv.cn/material/8e9fd77cb864f2dd5e70d093a4bba368/2020/0729/video/46a52af40f784973873a947ba2c69800.m3u8?auth_key=1703805847-bd32b649b3224faf9b409fa1dad62f85-0-2048a8685ea4a6c72fe3d70f5d8ea1ac",
            @"https://bp-resource-cc.bestv.cn/material/8e9fd77cb864f2dd5e70d093a4bba368/2020/0729/video/b46a89886b494fd0b24eb093c64a9bb5.m3u8?auth_key=1703867213-6937caa38adc4c6fad3a1c5ee5ca24b4-0-f5dca84810e89a826d927cc8ce539ee9",
            @"https://bp-resource-cc.bestv.cn/material/8e9fd77cb864f2dd5e70d093a4bba368/2020/0729/video/40dee38c0d0441f78b793a0e69bbd838.m3u8?auth_key=1703867515-b396c0cc97dc4bac93c717d10e56582e-0-2b3108b4e2cd76e684f17a0dc66cf814",
            @"https://bp-resource-cc.bestv.cn/material/8e9fd77cb864f2dd5e70d093a4bba368/2020/0729/video/739121c2f5614cfcb42180ade36b4d4c.m3u8?auth_key=1703867869-508341aa535b46f19641da965289dcf3-0-fe2552ccab6ac9e832efd48a7a842a16",
            @"https://bp-resource-cc.bestv.cn/material/8e9fd77cb864f2dd5e70d093a4bba368/2020/0729/video/64888bb7d36349759b752eb091232132.m3u8?auth_key=1703860665-a4c9ed73f4de4e25a7ce2a4e6219afb3-0-3869d240a42a03c943b362aa3c537fd5",
            @"https://bp-resource-cc.bestv.cn/material/8e9fd77cb864f2dd5e70d093a4bba368/2020/0729/video/dda301419e0f41628a56f6d2877fecb8.m3u8?auth_key=1703860684-fdff58e6a9ff4c8e83fa8916493c05e7-0-2851b0c74eea8f4f27093633d374bd47",
        ];
        
//        NSArray *urlList = @[@"https://xy2.v.netease.com/r/video/20190814/7db8102c-1b18-4a59-ac70-ec03137f1c2e.mp4?idx=1",
//                             @"https://crazynote.v.netease.com/2019/0811/6bc0a084ee8655bfb2fa31757a0570f4qt.mp4?idx=3",
//                             @"https://dhxy.v.netease.com/2019/0814/5757db881a2aff4543b7d9c846f3f415qt.mp4?idx=4",
//                             @"https://xy2.v.netease.com/r/video/20190110/bea8e70d-ffc0-4433-b250-0393cff10b75.mp4?idx=5",
//                             @"https://dh2.v.netease.com/2017/cg/fxtpty.mp4?idx=8",
//                             @"https://dhxy.v.netease.com/2019/0813/d792f23a8da810e73625a155f44a5d96qt.mp4?idx=12",
//        ];
        
        for (int i = 0; i < urlList.count; i ++) {
            XSTestModel *model = [[XSTestModel alloc] init];
            model.url       = [urlList objectAtIndex:i];
            model.videoName = [NSString stringWithFormat:@"猫和老鼠第%d集", i + 1];
            model.videoId   = [NSString stringWithFormat:@"%d", i + 200];
            [_dataArray addObject:model];
        }
        // 获取数据库中的数据
        NSArray *list = [[XSDataSaveManager sharedManager] lookDownloadAllData];
        // 更新数据状态
        if (list.count > 0) {
            [_dataArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                XSTestModel *model = (XSTestModel *)obj;
                // 更新数据
                [list enumerateObjectsUsingBlock:^(id  _Nonnull obj1, NSUInteger idx1, BOOL * _Nonnull stop1) {
                    XSTestModel *model1 = (XSTestModel *)obj1;
                    if ([model1.videoId isEqualToString:model.videoId]) {
                        _dataArray[idx] = model1;
                        *stop1 = YES;
                    }
                }];
            }];
        }
    }
    return _dataArray;
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    // 添加通知
    [self addNotification];
}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    // 移除通知
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationItem.title = @"list";
    self.view.backgroundColor = UIColor.orangeColor;
    
    // 全部开始 / 全部暂停
    UIBarButtonItem *rightButton = [[UIBarButtonItem alloc]initWithCustomView:self.allBtn];
    self.navigationItem.rightBarButtonItem = rightButton;
            
    [self createViewUI];
    
    // 更新全部开始按钮状态
    [self updateAllBtnState];
    
}

- (void)addNotification {
    // 下载进度
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(downLoadProgress:) name:XSDownloadM3u8ProgressNotification object:nil];
    // 下载状态改变
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(downLoadStateChange:) name:XSDownloadM3u8StateNotification object:nil];
}

-(void)updateAllBtnState {
    __block BOOL isSel = YES;
    [self.dataArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        XSTestModel *model = (XSTestModel *)obj;
        if (model.state != XSDownloadStatusFinish && model.state != XSDownloadStatusWaiting && model.state != XSDownloadStatusDownloading) {
            isSel = NO;
        }
    }];
    self.allBtn.selected = isSel;
}

-(void)createViewUI {
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.equalTo(self.view);
        make.top.mas_equalTo(GK_STATUSBAR_NAVBAR_HEIGHT);
    }];
    
    // 全部开始按钮选择状态
    self.allBtn.selected = [self checkNotDownloadData];
}

// 检查是否全部在下载队列中
-(BOOL)checkNotDownloadData {
    return NO;
}

// 全部开始 / 全部暂停
-(UIButton *)allBtn {
    if (!_allBtn) {
        _allBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _allBtn.frame = CGRectMake(0, 0, 50, 44);
        [_allBtn setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
        _allBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        [_allBtn setTitle:@"全部开始" forState:UIControlStateNormal];
        [_allBtn setTitle:@"全部暂停" forState:UIControlStateSelected];
        [_allBtn addTarget:self action:@selector(downAllBtn:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _allBtn;
}


-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableFooterView = [[UIView alloc] init];
        if (@available(iOS 11.0,*)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        
        [_tableView registerClass:[XSM3u8TableViewCell class] forCellReuseIdentifier:m3u8TableViewCellId];
    }
    return _tableView;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 65;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    XSM3u8TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:m3u8TableViewCellId forIndexPath:indexPath];
    if (self.dataArray.count > indexPath.row) {
        cell.model = [self.dataArray objectAtIndex:indexPath.row];
    }
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    XSTestModel *model = [self.dataArray objectAtIndex:indexPath.row];
    // 检查数据库中存在当前点击数据
    XSTestModel *downloadModel = [[XSDataSaveManager sharedManager] lookDownloadSingleData:model];
    if (downloadModel) {
        // 存在检查下载状态
        switch (downloadModel.state) {
            case XSDownloadStatusFinish: {
                
                NSLog(@"\n当前播放视频：%@\n路径：%@", downloadModel.videoName, downloadModel.locaM3u8lUrl);
                
                // 当前视频已下载完成，点击跳转播放页面
                XSPlayViewController *vc = [[XSPlayViewController alloc] init];
                vc.isM3u8 = YES;
                vc.modelM3u8 = downloadModel;
                [self.navigationController pushViewController:vc animated:YES];
            }
                break;
                
            case XSDownloadStatusDownloading:
                // 当前视频正在下载中，点击暂停下载
                [[XSDownloadManagerM3u8 sharedManager] pauseDownloadingTask:downloadModel];
                break;
                
            case XSDownloadStatusWaiting:
                // 当前视频等待下载中，点击暂停下载
                [[XSDownloadManagerM3u8 sharedManager] pauseDownloadingTask:downloadModel];
                break;
                
            case XSDownloadStatusPause:
                // 当前视频暂停中，点击加入下载队列开始下载
                [[XSDownloadManagerM3u8 sharedManager] addDownloadingTask:downloadModel];
                break;
                
            case XSDownloadStatusError:
                // 当前视频下载错误，点击加入下载队列重新下载
                [[XSDownloadManagerM3u8 sharedManager] addDownloadingTask:downloadModel];
                break;
                
            default:
                break;
        }
    } else {
        // 数据库中不存在加入数据库
        [[XSDownloadManagerM3u8 sharedManager] addDownloadingTask:model];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
    }
}

#pragma mark -- 下载信息通知
// 下载进度
- (void)downLoadProgress:(NSNotification *)noti {
    XSTestModel *downloadModel = noti.object;
    // 更新数据以及UI
    [self.dataArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        XSTestModel *model = (XSTestModel *)obj;
        if ([model.videoId isEqualToString:downloadModel.videoId]) {
            model = downloadModel;
            self.dataArray[idx] = model;
            // 主线程更新cell进度
            dispatch_async(dispatch_get_main_queue(), ^{
                XSM3u8TableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:idx inSection:0]];
                cell.model = downloadModel;
            });
            *stop = YES;
        }
    }];
}

// 下载状态改变
- (void)downLoadStateChange:(NSNotification *)noti {
    XSTestModel *downloadModel = noti.object;
    // 更新数据以及UI
    [self.dataArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        XSTestModel *model = (XSTestModel *)obj;
        if ([model.videoId isEqualToString:downloadModel.videoId]) {
            model = downloadModel;
            self.dataArray[idx] = model;
            // 主线程更新cell进度
            dispatch_async(dispatch_get_main_queue(), ^{
                XSM3u8TableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:idx inSection:0]];
                cell.model = downloadModel;
            });
            *stop = YES;
        }
    }];
    
    // 更新全部开始按钮状态
    [self updateAllBtnState];
}

// 全部开始 / 全部暂停按钮响应
-(void)downAllBtn:(UIButton *)sender {
    sender.selected = !sender.selected;
    if (sender.selected) {
        // 全部开始
        [[XSDownloadManagerM3u8 sharedManager] startAllDataDownloadTask:self.dataArray];
    } else {
        // 全部暂停
        [[XSDownloadManagerM3u8 sharedManager] pauseAllDataDownloadingTask];
    }
    // 刷新列表
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.dataArray removeAllObjects];
        [self.dataArray addObjectsFromArray:[[XSDataSaveManager sharedManager] lookDownloadAllData]];
        [self.tableView reloadData];
    });
}

- (void)dealloc {
    NSLog(@"dealloc - %@", self.class);
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
